# Try to find out if we have python
if(NOT CMAKE_VERSION VERSION_LESS 3.12)
  # Make sure we reevaluate find_package(Python ...) if the binding version changes
  if(NOT "${OPENRTI_FORCE_PYTHON2_BINDINGS}" STREQUAL "${OPENRTI_FORCE_PYTHON2_BINDINGS_CACHED}")
    get_cmake_property(_variableNames VARIABLES)
    foreach(_variableName ${_variableNames})
      if(_variableName MATCHES "^_?Python_.*$")
        unset(${_variableName} CACHE)
      endif()
    endforeach()
  endif()
  set(OPENRTI_FORCE_PYTHON2_BINDINGS_CACHED ${OPENRTI_FORCE_PYTHON2_BINDINGS} CACHE INTERNAL BOOL)

  # Ok, had issues with too old python versions, may be 2.6 is too crude ...
  if(OPENRTI_FORCE_PYTHON2_BINDINGS)
    find_package(Python 2.6 COMPONENTS Development)
  else()
    find_package(Python COMPONENTS Development)
    # Note that a version setting forces a find package to be tied to
    # that major version. Thus check for too old python afterwards.
    if(Python_Development_FOUND AND Python_VERSION VERSION_LESS 2.6)
      set(Python_Development_FOUND FALSE)
      message("Disabling python support with too old version.")
    endif()
   endif()
else()
# PYTHONLIBS_VERSION_STRING is available starting with 2.8.8
  if(NOT CMAKE_VERSION VERSION_LESS 2.8.8)
    find_package(PythonLibs)
  else()
    find_package(PythonLibsCompat)
  endif()
  # Ok, had issues with too old python versions, may be 2.6 is too crude ...
  if(PYTHONLIBS_FOUND AND
      PYTHONLIBS_VERSION_STRING VERSION_LESS 2.6)
    set(PYTHONLIBS_FOUND FALSE)
  endif()
  if(PYTHONLIBS_FOUND)
    string(REGEX REPLACE "^([0-9]+).([0-9]+).*$" "\\1" Python_VERSION_MAJOR "${PYTHONLIBS_VERSION_STRING}")
    string(REGEX REPLACE "^([0-9]+).([0-9]+).*$" "\\2" Python_VERSION_MINOR "${PYTHONLIBS_VERSION_STRING}")
    add_library(Python::Python UNKNOWN IMPORTED)
    set_property(TARGET Python::Python PROPERTY IMPORTED_LOCATION ${PYTHON_LIBRARIES})
    if(PYTHON_LIBRARIES_DEBUG)
      set_property(TARGET Python::Python PROPERTY IMPORTED_LOCATION_DEBUG ${PYTHON_LIBRARIES_DEBUG})
    endif()
    set_property(TARGET Python::Python PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${PYTHON_INCLUDE_DIRS})
    set(Python_Development_FOUND TRUE)
  else()
    set(Python_Development_FOUND FALSE)
  endif()
endif()

# If so, do what we need to do
if(Python_Development_FOUND)
  if(WIN32)
    set(INSTALL_PYTHON_DIRECTORY "Python${Python_VERSION_MAJOR}.${Python_VERSION_MINOR}/site-packages")
  else()
    set(INSTALL_PYTHON_DIRECTORY "${CMAKE_INSTALL_LIBDIR}/python${Python_VERSION_MAJOR}.${Python_VERSION_MINOR}/site-packages")
  endif()
  set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${INSTALL_PYTHON_DIRECTORY}")

  if(OPENRTI_ENABLE_RTI1516)
    add_subdirectory(rti1516)
  endif()
  if(OPENRTI_ENABLE_RTI1516E)
    add_subdirectory(rti1516e)
  endif()
endif()
